from nicegui import ui, events


def user_context_menu(evt: events.GenericEventArguments):
    print("user_context_menu")


def chat_context_menu(evt: events.GenericEventArguments):
    row = evt.args[-2]

    if row["id"] > 5:
        chat_menu.close()
        return

    chat_menu.clear()

    with chat_menu:
        ui.menu_item(
            f"第{evt.args[-1]+1}行的菜单:内容[{row}]",
            on_click=lambda: ui.notify(f"{row}"),
        )


user_columns = [
    {"name": "id", "label": "a", "field": "id", "required": True},
    {"name": "b", "label": "b", "field": "b"},
]
chat_columns = [
    {"name": "id", "label": "a", "field": "id", "required": True},
    {"name": "b", "label": "b", "field": "b"},
]

user_rows = [{"id": x, "b": "text"} for x in range(10)]
chat_rows = [{"id": x, "b": "text"} for x in range(10)]


# 思路是在表格上套一个容器，在容器上创建右键菜单
# 通过绑定表格的右键事件，控制菜单细节
def add_context_menu(table: ui.table):
    box = ui.element("div")
    table.move(box)
    with box:
        return ui.context_menu()


with ui.row():
    user_table = ui.table(columns=user_columns, rows=user_rows)

    with add_context_menu(user_table) as user_menu:
        ui.menu_item("a")

    chat_table = ui.table(columns=chat_columns, rows=chat_rows)
    chat_menu = add_context_menu(chat_table)

    user_table.on("rowContextmenu", user_context_menu)
    chat_table.on("rowContextmenu", chat_context_menu)


ui.run()
